/*
 页面父类基础界面
 */
import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';

/*
扫描界面(二维码,条码)

(暂只支持竖屏,对焦速度和识别快,横屏时摄像头方向错误,需要修改mobile_scanner.dart源文件???,底层使用原生新库)
适配android iOS mac:  https://pub.flutter-io.cn/packages/mobile_scanner  https://github.com/juliansteenbakker/mobile_scanner
dependencies:
  mobile_scanner: ^2.1.0
import 'package:mobile_scanner/mobile_scanner.dart';
使用:
android:需要在清单文件中添加摄像头权限;(不需要同作者github上的其他依赖配置和原生源码调用)


https://pub-web.flutter-io.cn/packages/qr_code_scanner_plus/install
(支持竖屏和横屏,对焦相对慢,此版本只维护,因为使用zxing for android and MTBBarcodescanner for iOS,官方也不更新):https://pub.flutter-io.cn/packages/qr_code_scanner
dependencies:
  qr_code_scanner_plus: ^2.0.10+1
import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart';
使用:
android:需要在清单文件中添加摄像头权限;(不需要同作者github上的其他依赖配置和原生源码调用)


此为qr_code_scanner,支持横竖屏,对焦速度同原生原来一样,比新版慢一点;



解决android中第三方依赖包重复冲突:
在原生Android开发项目的gradle中添加:
configurations {
    all*.exclude group: 'com.google.zxing', module: 'core'
}

2种exclude冲突依赖方式的区别
方式一：
implementation(“com.xxx.xxx:xxx”) {
exclude group: ‘com.xxx.xxx’
}
1.有多个引用依赖冲突时，exclude group会保留一个
2.只有1个依赖没有冲突时，exclude group也会保留一个

方式二：
configurations {
all*.exclude group: ‘com.xxx.xxx’
}
1.有多个引用依赖冲突时，all*.exclude会保留一个
2.只有1个依赖没有冲突时，all*.exclude不会保留，会有运行时找不到类的风险

 */
abstract class XPageScan2State extends XPageState{

  bool isEnableCamera;//是否开启摄像头

  XPageScan2State({
    super.isKeepPageState=false,
    super.xTag,
    super.handleAndFinishPageFunction,
    this.isEnableCamera=true,
  });

  QRViewController? qrViewController;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');

  @override
  Future<void> updateData({int pageIndex = 1}) async {
  }

  @override
  Widget getBodyWidget(BuildContext context) {

    /*
    //闪光灯
    ElevatedButton(
        onPressed: () async {
          await controller?.toggleFlash();
          setState(() {});
        },
        child: FutureBuilder(
          future: controller?.getFlashStatus(),
          builder: (context, snapshot) {
            return Text('Flash: ${snapshot.data}');
          },
        ));

    //切换摄像头
    ElevatedButton(
        onPressed: () async {
          await controller?.flipCamera();
          setState(() {});
        },
        child: FutureBuilder(
          future: controller?.getCameraInfo(),
          builder: (context, snapshot) {
            if (snapshot.data != null) {
              return Text(
                  'Camera facing ${describeEnum(snapshot.data!)}');
            } else {
              return const Text('loading');
            }
          },
        ));

    //暂停摄像头
    ElevatedButton(
      onPressed: () async {
        await controller?.pauseCamera();
      },
      child: const Text('pause',
          style: TextStyle(fontSize: 20)),
    )

    //重启摄像头
    ElevatedButton(
      onPressed: () async {
        await controller?.resumeCamera();
      },
      child: const Text('resume',
          style: TextStyle(fontSize: 20)),
    )

     */

    return XWidgetUtils.getLayoutStack(
        children: [
          isEnableCamera?_buildQrView():XWidgetUtils.getLayoutContainer(),
          getItemWidgetInStack(),
        ]
    );
  }


  //在Stack最上面,可添加对焦框,打开闪光灯,切换前后摄像头按钮,搜索框等
  @required
  Widget getItemWidgetInStack();

  //扫描结果响应
  @required
  void scanResultCallback(String? result);

  /////////////////////////////////////////////////////////

  @override
  void onPaused() {
    super.onPaused();
    qrViewController?.pauseCamera();
  }

  @override
  void onResumed() {
    super.onResumed();
    qrViewController?.resumeCamera();
  }

  Widget _buildQrView() {

    QrScannerOverlayShape qrScannerOverlayShape;
    if(XFlutterUtils.getIsScreenPortrait(contextOfScaffold??context)){
      //竖屏
      qrScannerOverlayShape=QrScannerOverlayShape(
        borderColor: Colors.white,
        borderRadius: 2,
        borderLength: 30,
        borderWidth: 1,
        cutOutWidth: 280,
        cutOutHeight: getQrScannerOverlayShapeHeight(),
        cutOutBottomOffset: getQrScannerOverlayShapeCutOutBottomOffset(),
      );
    }else{
      //横屏
      qrScannerOverlayShape=QrScannerOverlayShape(
        borderColor: Colors.white,
        borderRadius: 2,
        borderLength: 30,
        borderWidth: 1,
        cutOutWidth: 450,
        cutOutHeight: getQrScannerOverlayShapeHeight(),
        cutOutBottomOffset: getQrScannerOverlayShapeCutOutBottomOffset(),
      );
    }

    //BarcodeFormat.upcEanExtension 实测 iOS会在前面多一个0
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: qrScannerOverlayShape,
      onPermissionSet: (QRViewController ctrl, bool isHasPermission){
        if (!isHasPermission) {
          XLogUtils.printLog('---no Permission');
        }
      },
    );
  }

  //对焦框的样式
  // QrScannerOverlayShape _getQrScannerOverlayShape(){
  //   return QrScannerOverlayShape(
  //     borderColor: Colors.white,
  //     borderRadius: 2,
  //     borderLength: 30,
  //     borderWidth: 1,
  //     cutOutWidth: 280,
  //     cutOutHeight: 230,
  //     cutOutBottomOffset: getQrScannerOverlayShapeCutOutBottomOffset(),
  //   );
  // }

  //获得扫描框的位置设置(底边距离居中偏离, 0为居中, 正数:偏上)
  double getQrScannerOverlayShapeCutOutBottomOffset(){

    if(XFlutterUtils.getIsScreenPortrait(contextOfScaffold??context)){
      //竖屏
      return 105;//0则居中
    }

    //横屏
    return 50;//0则居中
  }

  //扫描框(对焦框)的高度
  double getQrScannerOverlayShapeHeight(){

    if(XFlutterUtils.getIsScreenPortrait(contextOfScaffold??context)){
      //竖屏
      return 230;
    }

    //横屏
    return 350;

  }

  int lastTime=0;

  void _onQRViewCreated(QRViewController controller) {

    qrViewController = controller;
    qrViewController!.scannedDataStream.listen((Barcode? scanData) {
      String? result=scanData?.code;
      XLogUtils.printLog('---scan result= $result, BarcodeFormat=${scanData?.format}');

      if(!XStringUtils.isEmpty(result)){
        //间隔2s
        int now=XDateUtils.getCurrentTime_ms();
        if(now-lastTime>2000){
          lastTime=now;

          //适配iOS 扫描自动在前面补0
          if(XFlutterUtils.isiOS() && scanData?.format==BarcodeFormat.ean13){
              if(result!.startsWith('0')){
                result=result.substring(1);
              }
          }


          XFlutterUtils.vibrate();
          scanResultCallback(result);
        }

      }

    });
  }


  @override
  void dispose() {
    qrViewController?.dispose();
    super.dispose();
  }



}